package com.lg.system.main.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.lg.system.main.dao.OnlineDao;
import com.lg.system.main.entity.Online;
import com.lg.system.main.service.OnlineService;
import com.lg.utils.StringUtils;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dl
 * @since 2018-03-28
 */
@Service
public class OnlineServiceImpl extends ServiceImpl<OnlineDao, Online> implements OnlineService {

	@Value(value="${spring.datasource.driverClassName}")
	private  String driverName;

    @Value(value="${spring.datasource.url}")
	private  String url;
	 
	@Value(value="${spring.datasource.password}")
	private  String password;

	@Value(value="${spring.datasource.username}")
	private  String username;
	
	@Autowired
	OnlineDao onlineDao;
	
	@Override
	public void initTable() {
		Map<String, Object> param=new HashMap<>(16);
		List<Online> onlines= onlineDao.selectByMap(param);
		if(null==onlines||onlines.isEmpty()){//如果数据表是空的则全部插入
			onlineDao.initTable();
		}else{//不是空的
			List<String> tableNames=getTableNames(onlines);
			List<Online> tables=onlineDao.selectTables();
			for(Online table:tables){
				if(!tableNames.contains(table.getTableName())){
					insert(table);
				}
			}
		}
	}
	
	private List<String> getTableNames(List<Online> onlines){
		List<String> names=new ArrayList<>();
		for(Online online:onlines){
			names.add(online.getTableName());
		}
		return names;
	}

	@Override
	public void down(Online online) {
		    AutoGenerator mpg = new AutoGenerator();
	        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
	        mpg.setGlobalConfig(globalConfig(online));
	        mpg.setDataSource(dbConfig());
	        // 策略配置
	        StrategyConfig strategy = new StrategyConfig();
	        if(StringUtils.isNotEmpty(online.getPrefix())){
	        	strategy.setTablePrefix(new String[] {online.getPrefix()});// 此处可以修改为您的表前缀
	        }
	        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
	        strategy.setInclude(new String[] {online.getTableName()}); // 需要生成的表
	        strategy.setSuperEntityClass("com.lg.utils.PageModel");// 自定义实体，公共字段
	        strategy.setSuperControllerClass("com.lg.common.base.BaseController");// 自定义 controller 父类
	        // 包配置
	        PackageConfig pc = new PackageConfig();
	        pc.setParent("com.lg."+online.getPosition());
	        //pc.setModuleName("main");
	        pc.setService("service");
	        pc.setController("controller");
	        pc.setMapper("dao");
	        mpg.setPackageInfo(pc);
	        myTemplate(mpg,online);
	         //自定义模板配置，可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改，
	         //放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置，也可以自定义模板名称
	         TemplateConfig tc = new TemplateConfig();
	         tc.setController("templates/online/controller.java");
	         tc.setEntity("templates/online/entity.java");
	         tc.setMapper("templates/online/mapper.java");
	         tc.setXml("templates/online/mapper.xml");
	         tc.setService("templates/online/service.java");
	         tc.setServiceImpl("templates/online/serviceImpl.java");
	         mpg.setTemplate(tc);
	         mpg.setStrategy(strategy);
	         mpg.execute();
	}
	
	
    private  DataSourceConfig dbConfig(){
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        dsc.setTypeConvert(new MySqlTypeConvert(){
            // 自定义数据库表字段类型转换【可选】
            @Override
            public DbColumnType processTypeConvert(String fieldType) {
                return super.processTypeConvert(fieldType);
            }
        });
        dsc.setDriverName(driverName);
        dsc.setUsername(username);
        dsc.setPassword(password);
        dsc.setUrl(url);
        return dsc;
    }
    
    private GlobalConfig globalConfig(Online online){
         GlobalConfig gc = new GlobalConfig();
         if(online.getLocation()==null){
        	 gc.setOutputDir("D://"); 
         }else{
        	 gc.setOutputDir(online.getLocation()+"://"); 
         }
         gc.setFileOverride(online.getFileOverride()==1);
         gc.setActiveRecord(true);// 不需要ActiveRecord特性的请改为false
         gc.setEnableCache(online.getEnableCache()==0);// XML 二级缓存
         gc.setBaseResultMap(online.getResultmap()==0);// XML ResultMap
         gc.setBaseColumnList(online.getColumnList()==0);// XML columList
         //.setKotlin(true) 是否生成 kotlin 代码
         gc.setAuthor(online.getAuthor());
         // 自定义文件命名，注意 %s 会自动填充表实体属性！
         gc.setMapperName("%sDao");
         gc.setXmlName("%sMapper");
         gc.setServiceName("%sService");
         gc.setServiceImplName("%sServiceImpl");
         gc.setControllerName("%sController");
         gc.setOpen(online.getOpen()==0);
         return gc;
    	
    }
    
    private void myTemplate(AutoGenerator mpg,Online online){
    	// 注入自定义配置，可以在 VM 中使用 cfg.abc 【可无】
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<String, Object>();
                this.setMap(map);
            }
        };
        // 自定义 //html模板 生成
        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
        focList.add(new FileOutConfig("/templates/online/index.html.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
            	 String local="";
            	 if(online.getLocation()==null){
            		 local=("D://"); 
                 }else{
                	 local=(online.getLocation()+"://com/lg/"+online.getPosition().replace(".", "\\")+"/index.html"); 
                 }
                return local;
            }
        });
        
        focList.add(new FileOutConfig("/templates/online/add.html.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
            	 String local="";
            	 if(online.getLocation()==null){
            		 local=("D://"); 
                 }else{
                	 local=(online.getLocation()+"://com/lg/"+online.getPosition().replace(".", "\\")+"/add.html"); 
                 }
                return local;
            }
        });
        
        focList.add(new FileOutConfig("/templates/online/edit.html.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
            	 String local="";
            	 if(online.getLocation()==null){
            		 local=("D://"); 
                 }else{
                	 local=(online.getLocation()+"://com/lg/"+online.getPosition().replace(".", "\\")+"/edit.html"); 
                 }
                return local;
            }
        });
        
        //js模板
        focList.add(new FileOutConfig("/templates/online/add.js.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
            	 String local="";
            	 if(online.getLocation()==null){
            		 local=("D://"); 
                 }else{
                	 local=(online.getLocation()+"://com/lg/"+online.getPosition().replace(".", "\\")+"/add.js"); 
                 }
                return local;
            }
        });
        focList.add(new FileOutConfig("/templates/online/edit.js.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
            	 String local="";
            	 if(online.getLocation()==null){
            		 local=("D://"); 
                 }else{
                	 local=(online.getLocation()+"://com/lg/"+online.getPosition().replace(".", "\\")+"/edit.js"); 
                 }
                return local;
            }
        });
        focList.add(new FileOutConfig("/templates/online/index.js.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
            	 String local="";
            	 if(online.getLocation()==null){
            		 local=("D://"); 
                 }else{
                	 local=(online.getLocation()+"://com/lg/"+online.getPosition().replace(".", "\\")+"/index.js"); 
                 }
                return local;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
    	
    }
}
